<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>数组扁平化</title>
</head>
<body>
  <!-- 
    数组扁平化: 取出嵌套数组(多维)中的所有元素放到一个新数组(一维)中
            如: [1, [3, [2, 4]]]  ==>  [1, 3, 2, 4]
   -->
  <script>
    /*
    方法一: 递归 + reduce() + concat()
    */
    Array.prototype.flatten = function () {
      return this.reduce((pre, item) => {
        if (Array.isArray(item)) {
          return pre.concat(item.flatten())
        } else {
          return pre.concat(item)
        }
      }, [])
    }
    
    /*
    方法二: ... + some() + concat()
    */
    Array.prototype.flatten2 = function () {
      let arr = [].concat(...this)
      while (arr.some(item => Array.isArray(item))) {
        arr = [].concat(...arr)
      }
      return arr
    }
  </script>
  
  <script>
    // [1]  ---> [1, 3, 2, 4]
    // [3, [2, 4]] --> [3] --> [3, 2, 4]
    // [2, 4] --> [2, 4]
    console.log([1, [3, [2, 4]]].flatten())
    // [1, 3, [2, 4]] --> [1, 3, 2, 4]
    console.log([1, [3, [2, 4]]].flatten2())
  </script>
</body>
</html>